<?php

namespace addons\aliossapiupload\controller;

use think\addons\Controller;
use app\common\library\Upload;
use OSS\OssClient;



class Index extends Controller
{

    /**
     * 测试页面
     */
    public function index()
    {
        $this->check_alioss_install_status();
        return $this->view->fetch();
    }


    /**
     * 上传接口
     */
    public function upload()
    {
        //此处可以自行写方法校验权限

        $config = get_addon_config('alioss');
        //
        $oss = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);
        // halt($oss);
        $chunkid = $this->request->post("chunkid");
        if ($chunkid) {
            $action = $this->request->post("action");
            $chunkindex = $this->request->post("chunkindex/d");
            $chunkcount = $this->request->post("chunkcount/d");
            $filesize = $this->request->post("filesize");
            $filename = $this->request->post("filename");
            $method = $this->request->method(true);
            $key = $this->request->post("key");
            $uploadId = $this->request->post("uploadId");

            if ($action == 'merge') {
                //合并分片
                if ($config['uploadmode'] == 'server') {
                    $attachment = null;
                    //合并分片文件
                    try {
                        $upload = new Upload();
                        $attachment = $upload->merge($chunkid, $chunkcount, $filename);
                    } catch (UploadException $e) {
                        $this->error($e->getMessage());
                    }
                }

                $etags = $this->request->post("etags/a", []);
                if (count($etags) != $chunkcount) {
                    $this->error("分片数据错误");
                }
                $listParts = [];
                for ($i = 0; $i < $chunkcount; $i++) {
                    $listParts[] = array("PartNumber" => $i + 1, "ETag" => $etags[$i]);
                }
                try {
                    $ret = $oss->completeMultipartUpload($config['bucket'], $key, $uploadId, $listParts);
                } catch (\Exception $e) {
                    $this->error($e->getMessage());
                }

                $result = json_decode(json_encode(simplexml_load_string($ret['body'], "SimpleXMLElement", LIBXML_NOCDATA)), true);
                if (!isset($result['Key'])) {
                    $this->error("上传失败");
                } else {
                    $this->success("上传成功1", '', ['url' => "/" . $key, 'fullurl' => cdnurl("/" . $key, true)]);
                }
            } else {
                //默认普通上传文件
                $file = $this->request->file('file');
                try {
                    $upload = new Upload($file);
                    $file = $upload->chunk($chunkid, $chunkindex, $chunkcount);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                try {
                    //上传分片到OSS
                    $ret = $oss->uploadPart($config['bucket'], $key, $uploadId, ['fileUpload' => $file->getRealPath(), 'partNumber' => $chunkindex + 1]);
                } catch (\Exception $e) {
                    $this->error($e->getMessage());
                }

                $this->success("上传成功2", "", [], 3, ['ETag' => $ret]);
            }
        } else {
            $attachment = null;
            //默认普通上传文件
            $file = $this->request->file('file');
            
            try {
                $upload = new Upload($file);
                $attachment = $upload->upload();
              
            } catch (UploadException $e) {
                $this->error($e->getMessage());
            }


            //文件绝对路径
            $filePath = $upload->getFile()->getRealPath() ?: $upload->getFile()->getPathname();
            
            try {
                // halt($filePath);
                $ret = $oss->uploadFile($config['bucket'], ltrim($attachment->url, "/"), $filePath);
                
                // halt($ret);//成功不做任何操作
            } catch (\Exception $e) {
                // halt($attachment);
                $attachment->delete();
                @unlink($filePath);
                $this->error("上传失败2",$oss);
            }

            $data['code'] = 1;
            $data['data'] = ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)];
            $data['msg'] = '上传成功4';
            return json($data);
            // $this->success("上传成功3", '', ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
        }
        return;
    }

    /**
     * 检查阿里云oss配置环境
     */
    private function check_alioss_install_status()
    {
        $config = get_addon_config('alioss');
        if(!$config){
            $this->error('请安装Fastadmin官方的阿里云OSS上传插件！');
        }
    }

    


}
